/*
 * @Author: Qimu
 * @Date: 2020-04-19 05:46:51
 * @LastEditors: Qimu
 * @LastEditTime: 2020-06-23 01:52:13
 * @Description: file content
 * @FilePath: \vue-admin-koa2\koa2_api\module\middleware\checkToken.js
 */
const tools = require('../utlis/tools');
const config = require('../config/config');
const jwt = require('jsonwebtoken');//签发Token

const checkToken = {
  admin: () => {
    return async (ctx, next) => {
      let token = ctx.request.header.authorization;
      console.log('token', token);
      let decode = jwt.decode(token.split(' ')[1], config.accessJwt.secret);//解析jwt payload数据
      console.log('decode', decode);
      let currentTime = (new Date()).getTime() / 1000;//获取当前时间戳(秒s)
      if (token) {
        if (currentTime <= decode.exp) {
          ctx.body = {
            'meta': {
              'status': 200,
              'message': 'Token解析成功!'
            }
          }
          await next();
        } else {
          ctx.body = {
            'data': {
              'token': token,
            },
            'meta': {
              'status': 401,
              'message': 'Token过期!'
            }
          };
        }
      } else {  // 没有token
        ctx.body = {
          'meta': {
            'status': 500,
            'message': '没有Token!'
          }
        }
      }
    }
  }
}

module.exports = checkToken;